require "proto/equip/message/ReqWearMessage"
require "proto/equip/message/ReqUnwearMessage"
require "proto/equip/message/ReqChangeMessage"
require "proto/equip/message/ReqRefineMessage"
require "proto/equip/message/ReqResolveEquipMessage"
require "proto/equip/message/ReqOneKeyWearOrUnWearMessage"
require "proto/equip/message/ReqEquipUpLvMessage"
require "proto/equip/message/ReqRefineOneClickMessage"
require "proto/equip/message/ReqSwitchSuitMessage"
require "proto/equip/message/ReqEquipQuickUpLvMessage"
equipHandler = equipHandler or {};
G.serverData = G.serverData or {};

function equipHandler.receiveWear(msg)
    -- log("equipHandler.receiveWear");
    -- dataTable.PrintTable(msg); 
    if msg.state == 0 then
        local part = logicMgr.EquipManager.getEquipPartbyModelId(msg.item.itemModelId);
        if logicMgr.EquipManager.getEquip(msg.partnerId,part) ~= nil then
            logicMgr.EquipManager.delEquip(tostring(msg.partnerId),part);
        end
        --[[local item = ClientEquipData.New();
        item["itemId"] = tostring(msg.item.itemId);
        item["itemModelId"] = msg.item.itemModelId;
        item["num"] = msg.item.num;
        item["partnerId"] = tostring(msg.partnerId);
        if msg.item.parameters then
            local refine = decodeJsonStrToTabel(msg.item.parameters);
            item["curRfLevel"] = tonumber(refine["STRENGTH_LEVEL"]);
            item["exp"] = tonumber(refine["STRENGTH_EXP"]);
        end]]
        local partnerId = tostring(msg.partnerId)
        logicMgr.EquipManager.addItemData(msg.item,-1,"",partnerId);
        logicMgr.HeroManager.updateHeroBaseAttr(partnerId,true);
        FireEvent(Config.EventType.Fresh_Equip);
        -- FireEvent(Config.EventType.Fresh_EquipWear);
    end
end

function equipHandler.receiveUnwear(msg)
    -- log("equipHandler.receiveUnwear");
    -- dataTable.PrintTable(msg); 
    if msg.state == 0 then
        local partnerId = tostring(msg.partnerId);
        local _equipIndex = tonumber(msg.equipIndex)
        
        logicMgr.EquipManager.delEquip(partnerId,_equipIndex);
        logicMgr.HeroManager.updateHeroBaseAttr(partnerId,true);
        FireEvent(Config.EventType.Fresh_Equip);
        -- FireEvent(Config.EventType.Fresh_EquipUnWear);
    end
end

function equipHandler.receiveChange(msg)
    --log("equipHandler.receiveChange");
    --dataTable.PrintTable(msg);
    if msg.state == 0 then
        local partnerId = tostring(msg.partnerId);
        local otherPartnerId = tostring(msg.otherPartnerId);

        local pOld = HeroManager.CalcHeroPower(partnerId,true,true)
        logicMgr.EquipManager.changeEquip(partnerId,otherPartnerId,msg.equipIndex);
        local pNew = HeroManager.CalcHeroPower(partnerId,true)
        local showFlag = pOld ~= pNew
        logicMgr.HeroManager.updateHeroBaseAttr(partnerId,showFlag);
        logicMgr.HeroManager.updateHeroBaseAttr(otherPartnerId);
        FireEvent(Config.EventType.Fresh_Equip);
    end
end

function equipHandler.receivePartnerEquips(msg)
    --log("equipHandler.receivePartnerEquips");
	--dataTable.PrintTable(msg);
    if msg.state == 0 then
        for i = 1, #msg.partnerEquips do
            local partnerEquips = msg.partnerEquips[i];
            local partnerId = partnerEquips.partnerId;
            local items = partnerEquips.items;
            for j = 1, #items do
                --[[local item = ClientEquipData.New();
                item["itemId"] = tostring(items[j].itemId);
                item["itemModelId"] = items[j].itemModelId;
                item["num"] = items[j].num;
                item["partnerId"] = tostring(partnerId);
                if items[j].parameters ~= nil then
                    local refine = decodeJsonStrToTabel(items[j].parameters);
                    item["curRfLevel"] = tonumber(refine["STRENGTH_LEVEL"]);
                    item["exp"] = tonumber(refine["STRENGTH_EXP"]);
                end]]
                logicMgr.EquipManager.addItemData(items[j],-1,"",partnerId);
            end
            logicMgr.HeroManager.updateHeroBaseAttr(partnerId, nil, nil, nil, true);
        end
        FireEvent(Config.EventType.Fresh_Equip);
    end
end

--精炼
function equipHandler.receiveRefine(msg)
    --log("equipHandler.receiveRefine");
    --dataTable.PrintTable(msg);
    if msg.state ~= 0 then return end
    local equip = EquipManager.getEquipbyId(msg.item.itemId)
    if not equip then return end
    local oldLevel = equip.curRfLevel
    local newLevel = equip.curRfLevel
    if msg.item.parameters ~= nil then
        local refine = decodeJsonStrToTabel(msg.item.parameters);
        newLevel = tonumber(refine["STRENGTH_LEVEL"])
        logicMgr.EquipManager.setEquipRefine(msg.partnerId,msg.item.itemId,newLevel,tonumber(refine["STRENGTH_EXP"]))
    end
    if newLevel ~= oldLevel then
        logicMgr.HeroManager.updateHeroBaseAttr(msg.partnerId, true,nil,nil,nil,true)
    else
        logicMgr.HeroManager.updateHeroBaseAttr(msg.partnerId)
    end
    FireEvent(Config.EventType.Fresh_Refine);
    FireEvent(Config.EventType.ReFreshHeroPower)
    -- 英雄-装备-精炼
    AudioManager.Play(2015)
end

function equipHandler.receiveResolveEquip(msg)
    --log("equipHandler.receiveResolveEquip");
    --dataTable.PrintTable(msg);
    if msg.state == 0 then
        FireEvent(Config.EventType.EquipResolve);
    end
end

function equipHandler.sendRefine(partnerId,equipIndex,items)
    local req = ReqRefineMessage.New();
    req.partnerId = partnerId;
    req.equipIndex = equipIndex;
    req.items = items;
    local byte_size = #items * 16 + 12;
    sendSmartReqMessage(req, nil, nil, byte_size)
end

function equipHandler.sendUnWear(partnerId, equipIndex)
    local req =  ReqUnwearMessage.New();
    req.partnerId = partnerId;
    req.equipIndex = equipIndex;
    sendReqMessage(req);
end

function equipHandler.sendWear(partnerId, itemId)
    local req =  ReqWearMessage.New();
    req.partnerId = partnerId;
    req.itemId = itemId;
    sendReqMessage(req);
end

function equipHandler.SendQuickEquipBreak(partnerId)
    local req = ReqEquipQuickUpLvMessage.New()
    req.partnerId = partnerId
    sendReqMessage(req)
end

function equipHandler.ResQuickEquipBreak(msg)
    FireEvent(Config.EventType.QuickEquipBreak,msg)
end

function equipHandler.sendOneKeyWearOrUnWear(partnerId, data )
    local req =  ReqOneKeyWearOrUnWearMessage.New();
    req.partnerId = partnerId
    req.itemList = data
    sendReqMessage(req);
end

function equipHandler.receiveOneKeyWearOrUnWear( msg )

    if msg and msg.state == 0 then
        local list_items = msg.equipList
        local partner_id = tostring(msg.partnerId)
        for i=1, 4 do
            local item = list_items and list_items[i]
            if item ~= nil and tostring(item.itemId) ~= "0" then 
                local flag = nil
                if logicMgr.EquipManager.getEquip(partner_id, i) ~= nil then
                    logicMgr.EquipManager.delEquip(partner_id, i) 
                else
                    flag = true
                end 
                logicMgr.EquipManager.addItemData(item, -1, "", partner_id)
            else  
                logicMgr.EquipManager.delEquip(partner_id, i) 
            end
        end
        logicMgr.HeroManager.updateHeroBaseAttr(partner_id, true)
        FireEvent(Config.EventType.Fresh_Equip)
    end

end

function equipHandler.sendChange(partnerId, equipIndex,otherPartnerId)
    local req =  ReqChangeMessage.New();
    req.partnerId = partnerId;
    req.equipIndex = equipIndex;
    req.otherPartnerId = otherPartnerId;
    sendReqMessage(req);
end

function equipHandler.sendResolveEquip(tableEquip)
    local req = ReqResolveEquipMessage.New();
    local items  ={};
    for i = 1, #tableEquip do
        local item = ItemInfo.New();
        item.itemId = tableEquip[i].itemId;
        item.itemModelId = tableEquip[i].itemModelId;
        item.quality = tableEquip[i].quality;
        item.num = tableEquip[i].num;
        item.isbind = 0;
        item.gridId = tableEquip[i].gridId;
        item.lostTime = 0;
        item.attributes = {};
        item.parameters = "";
        table.insert(items,item);
    end
    req.items =items;
    sendReqMessage(req);
end

-- 批量操作装备列表
-- <field class="id" name="partnerId" explain="伙伴Id"></field>
-- <field class="int" name="equipIndex" explain="装备位置"></field>
-- <field class="com.game.item.bean.ItemInfo" name="item" explain="装备"></field>
-- --ItemInfo
-- self.itemId --- @type number 物品唯一Id 
-- self.itemModelId --- @type number 物品模板Id 
-- self.quality --- @type number 物品品质 
-- self.num --- @type number 物品数量 
-- self.isbind --- @type number 是否绑定 1是 0否  
-- self.gridId --- @type number 道具所在格子Id 
-- self.lostTime --- @type number 过期时间

function equipHandler.receiveOperateEquip(msg)
    if msg and msg.equipList then
        local wear_flag = false
        local unwear_flag = false
        for k, v in pairs(msg.equipList) do
            if v ~= nil then
                local partnerId = tostring(v.partnerId)
                local part = v.equipIndex
                if v.item ~= nil then
                    if wear_flag == false then
                        wear_flag = true
                    end
                    if logicMgr.EquipManager.getEquip(partnerId, part) ~= nil then
                        logicMgr.EquipManager.delEquip(partnerId, part)
                    end 
                    logicMgr.EquipManager.addItemData(v.item, -1, "", partnerId)
                    logicMgr.HeroManager.updateHeroBaseAttr(partnerId, true)
                else
                    if unwear_flag == false then
                        unwear_flag = true
                    end
                    logicMgr.EquipManager.delEquip(partnerId, part)
                    logicMgr.HeroManager.updateHeroBaseAttr(partnerId, true)
                end
            end
        end
        FireEvent(Config.EventType.Fresh_Equip)
        -- if wear_flag == true then
        --     FireEvent(Config.EventType.Fresh_EquipWear)
        -- end
        -- if unwear_flag == true then
        --     FireEvent(Config.EventType.Fresh_EquipUnWear)
        -- end

    end
end

function equipHandler.ReqEquipUpLv(partnerId,equipIndex)
    local req = ReqEquipUpLvMessage.New()
    req.partnerId = partnerId
    req.equipIndex = equipIndex
    sendReqMessage(req)
end

function equipHandler.ResEquipUpLv(msg)
    FireEvent(Config.EventType.UpdataEquipLv,msg)
end

----------------------------------------------------------------------------------
require "proto/equip/message/ReqSmartWearMessage" 
require "proto/equip/message/ReqSmartWearExMessage" 
require "proto/equip/message/ReqGetSmartWearPriorityMessage" 
require "proto/equip/message/ReqSetSmartWearPriorityMessage" 
--智能穿戴
function equipHandler.sendSmartWearEquip( smart_wear_list, smart_unwear_list, priority_data )
    equipHandler.refreshHeroList = true
    local req = ReqSmartWearMessage.New()
    local items  ={}
    local byte_size = 0
    for _, v in pairs(smart_wear_list) do
        local item = SmartWearItem.New()
        item.partnerId = v.partnerId
        item.itemId1 = v.itemId1
        item.itemId2 = v.itemId2
        item.itemId3 = v.itemId3
        item.itemId4 = v.itemId4
        table.insert(items, item)
        byte_size = byte_size+40
    end
    req.wearList =items

    local unwear_items  ={}
    for _, v in pairs(smart_unwear_list) do
        local item = SmartUnWearItem.New()
        item.partnerId = v.partnerId 
        item.indexList = {}
        if v.index1 then
            table.insert(item.indexList , v.index1)
        end
        if v.index2 then
            table.insert(item.indexList , v.index2)
        end
        if v.index3 then
            table.insert(item.indexList , v.index3)
        end
        if v.index4 then
            table.insert(item.indexList , v.index4)
        end 
        table.insert(unwear_items, item)
        byte_size = byte_size + 20
    end
    req.unwearList = unwear_items

    -- req.priority1 = priority_data and priority_data.priority1 or {} 
    -- req.priority2 = priority_data and priority_data.priority2 or {}
    -- req.priority3 = priority_data and priority_data.priority3 or {}
    byte_size = byte_size + 100
    sendSmartReqMessage(req, nil, nil, byte_size)
end

function sendSmartReqMessage(reqProto, showWaiting, callback, byte_size)
    if Config.DEBUG_DUMP_MSG and reqProto.msgId ~= 100201 then
        dataTable.PrintTableTogether(string.format("send msg, msgid -> %d", reqProto.msgId), reqProto);
    end

    if LocalServer.ContainsReq(reqProto.msgId) then
        LocalServer.Receive(reqProto, callback)
        return
    end
    if byte_size < 1024 or byte_size == nil then
        byte_size = 1024
    end
    local buff = WebMsgMgr:createByteBuffSize(byte_size)
    buff:WriteInt32(1227)
    buff:WriteInt32(0);
    buff:WriteInt32(0);
    buff:WriteInt32(0);
    buff:WriteInt32(0);
    reqProto:WriteBuff(buff);

    buff:SetInt(4, buff.Length - 8);

    if showWaiting == nil then
        showWaiting = 1;
    end

    if showWaiting == 1 then
        table.insert(NetMsgDecoder.hasSendMsgOrder, WebMsgManager.MsgOrder);
    end

    if callback ~= nil and NetMsgDecoder.callbackFun[WebMsgManager.msgOrder] == nil then
        NetMsgDecoder.callbackFun[WebMsgManager.MsgOrder] = callback;
    end 
    WebMsgMgr:SendByteBuffMsg(reqProto.msgId, buff, logicMgr.LoginManager.GetServerName(), showWaiting, callback);

end

-- 智能穿戴返回
function equipHandler.receiveSmartWearEquip(msg) 
    if isOpenUI(PanelNames.UIEquipmentAllocation) then
        local ui_equipment_allocation = CtrlManager.GetCtrl(PanelNames.UIEquipmentAllocation)
        ui_equipment_allocation.ResSmartWear()
    end
end

--
-- 请求返回最新智能列表
function equipHandler.sendReqGetSmartWearPriority() 
    local req = ReqGetSmartWearPriorityMessage.New() 
    sendReqMessage(req)
end

-- 请求重置当前最新智能列表
function equipHandler.sendReqSetSmartWearPriority( data )  
    local req = ReqSetSmartWearPriorityMessage.New() 
    req.priority1 = data and data.priority1 or {} 
    req.priority2 = data and data.priority2 or {}
    req.priority3 = data and data.priority3 or {}
    sendReqMessage(req)
end

-- 最新智能列表返回
function equipHandler.receiveGetSmartWearPriority( msg )
    if isOpenUI(PanelNames.UIEquipmentAllocation) then
        local ui_equipment_allocation = CtrlManager.GetCtrl(PanelNames.UIEquipmentAllocation)
        ui_equipment_allocation.UpdatePriorityData( msg )
    end
end


-- 重置当前最新智能列表返回
function equipHandler.receiveSetSmartWearPriority( msg )
end
--一键精炼
function equipHandler.ReqRefineOneClick(partnerId)
    local msg = ReqRefineOneClickMessage.New()
    msg.partnerId = partnerId
    sendReqMessage(msg)
end
--一键精炼返回
---@param msg ResRefineOneClickMessage
function equipHandler.ResRefineOneClick(msg)
    local flag = false
    local mgr = logicMgr.EquipManager
    if msg.state ~= 0 then return end
    local oldLevelList = {}
    local equipList = {}
    for k,v in pairs(msg.item) do
        local itemId = tostring(v.itemId)
        local old = mgr.getEquipbyId(itemId,true)
        local oldLv = 0
        local oldExp = 0
        if old == nil then
            logError("找不到装备 itemId "..itemId)
        else
            oldLv = old.curRfLevel
            oldExp = old.exp
        end
        oldLevelList[itemId] = oldLv
        logicMgr.EquipManager.addItemData(v,-1,"",tostring(msg.partnerId))
        local _new = mgr.getEquipbyId(itemId,true)
        if oldLv ~= _new.curRfLevel then
            flag = true
        end
        if oldLv ~= _new.curRfLevel or oldExp ~= _new.exp then
            table.insert(equipList,_new)
        end
    end
    if flag then
        logicMgr.HeroManager.updateHeroBaseAttr(msg.partnerId, true,nil,nil,nil,true)
    end
    FireEvent(Config.EventType.Fresh_Refine);
    showUI(PanelNames.UIRefineResult,msg.partnerId,oldLevelList,equipList,msg.tempItemInfos)
    -- 英雄-装备-精炼
    AudioManager.Play(2015)
end

function equipHandler.sendSwitchSuit(pId,suitType,eIndex)
    local reqSwitchSuitMessage = ReqSwitchSuitMessage.New()
    reqSwitchSuitMessage.partnerId = pId
    reqSwitchSuitMessage.suitType = suitType
    reqSwitchSuitMessage.equipIndex = eIndex
    sendReqMessage(reqSwitchSuitMessage)
end

function equipHandler.receiveSwitchSuit(msg)
    local partnerId = msg.partnerId
    local suitId = nil

    local pOld = HeroManager.CalcHeroPower(partnerId,true,true)

    for k, _equipItem in pairs(msg.equipList) do
        local newItem = _equipItem.item
        logicMgr.EquipManager.addItemData(newItem,-1,"",partnerId);
        local item = logicMgr.EquipManager.getEquipbyId(newItem.itemId)
        if suitId == nil then
            suitId = item.suit
        end
    end

    local pNew = HeroManager.CalcHeroPower(partnerId,true)

    if pOld~=pNew then
        logicMgr.HeroManager.updateHeroBaseAttr(partnerId,true,nil,nil,nil,true)
    else
        logicMgr.HeroManager.updateHeroBaseAttr(partnerId,false)
    end

    if suitId then
        UISysTips.AddMsg(getLanguage("EquipSwitchToSuit"..suitId))
    end

    FireEvent(Config.EventType.Fresh_Equip);
    FireEvent(Config.EventType.Fresh_Suit_Switch);
end